//
//  WBComposeViewController.swift
//  微博(swift)
//
//  Created by 汤米 on 16/4/24.
//  Copyright © 2016年 汤米. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBComposeViewController: UIViewController {
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
    }

    // MARK: -  设置视图
    private func setUpUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        setUpNav()
        
        view.addSubview(composeTextView)
        view.addSubview(composeToolBar)
        composeTextView.addSubview(pictureView)
        
        
        composeTextView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)

            
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        clickToolBarButton()
        

        pictureView.snp_makeConstraints { (make) -> Void in
            
            make.size.equalTo(CGSize(width: kScreenW - 20, height: kScreenW - 20))
            make.leading.equalTo(10)
            make.top.equalTo(composeTextView).offset(100)
        }
        
        //监听弹出图片控制器
        pictureView.ComposePictureViewClosure = { [weak self] in
            
            self?.selectPictures()
        }
        
        //监听键盘弹出frame的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    // MARK: -  监听键盘弹出frame改变方法
    func keyboardWillChangeFrame(notification: NSNotification) {
        
        // 获取键盘的rect
        let rect = (notification.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        // 更新composeToolBar约束
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - kScreenH)

        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
        
        //注册通知观察者  监听表情键盘删除按钮的点击事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteButtonWasClicked", name: deleteButtonWasClickedNotification, object: nil)
        
        
        //注册通知观察者  监听表情键盘按钮的点击事件
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtonWasClicked:", name: emoticonButtonWasClickedNotification, object: nil)
        
    }
    
    // MARK: -  表情键盘按钮被点击时发送通知所调用的事件
    func emoticonButtonWasClicked(notification: NSNotification) {
        
//        print("表情按钮被点击了")
//        print(notification.object)
        
        guard let emoticon = notification.object as? WBEmoticonModel else {
            
            return
        }
        
        if emoticon.isEmoji {
            
            let code = ((emoticon.code ?? "") as NSString).emoji()
            
            composeTextView.insertText(code)
        }else {
            
            //得到之前的附文本
            let previousAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)

            let path = "\(emoticon.path!)\(emoticon.png!)"
            let image = UIImage(named: path, inBundle: WBEmoticonTool.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            
            //得到行高
            let lineHeight = composeTextView.font!.lineHeight
            
            //初始化一个文本附件
            let att = WBTextAttachment()
            att.emoticonModel = emoticon
            //设置bounds
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            att.image = image
            
            //初始化一个不可变附文本
            let attr = NSAttributedString(attachment: att)
            let selectedRange = composeTextView.selectedRange
//            previousAttr.insertAttributedString(attr, atIndex: selectedRange.location)
            //替换选中部分的附文本
            previousAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            //设置附文本字体大小
            previousAttr.addAttribute(NSFontAttributeName, value: composeTextView.font!, range: NSMakeRange(0, previousAttr.length))
            
            composeTextView.attributedText = previousAttr
            print("哈哈哈的很好的话好的好的")
            composeTextView.selectedRange = NSMakeRange(selectedRange.location + 1, 0)
        }
    }
    
    
    // MARK: -  表情键盘删除按钮删除textView上的文字的点击事件
    func deleteButtonWasClicked() {
        
        composeTextView.deleteBackward() 
    }
    
    
    // MARK: -  监听toolBar按钮点击
    private func clickToolBarButton() {
        
        composeToolBar.composeToolBarColsure = {[weak self](type: WBComposeToolBarType) in
            switch type{
            case .Picture:
                print("图片")
                self?.selectPictures()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("表情")
                self?.switchKeyborad()
            case .Add:
                print("+")
            }
        }
    }
    
    // MARK: -  设置导航栏
    private func setUpNav() {
        
        navigationController?.navigationBar.tintColor = themeColor
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "clickCancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "clickSend")
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
    }
    
    // MARK: -  发送按钮的点击事件
    @objc private func clickSend() {
                
        var result: String = String()
        composeTextView.attributedText.enumerateAttributesInRange(NSMakeRange(0, composeTextView.attributedText.length), options: []) { (dictInfo, range, _) -> Void in
            
            if let att = dictInfo["NSAttachment"] as? WBTextAttachment{
                result += att.emoticonModel?.chs ?? ""
            }else{
                // 从我们的富文本中 截取出里面的文字
                let name = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                
                result += name
                
            }
        }
        
        if pictureView.images.count == 0 {
            
            releaseWordWeiBo(result)
        }else {
            
            releasePictureWeiBo(result)
        }
 
    }
    
    // MARK: -  取消按钮的点击事件
    @objc private func clickCancel() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: -  自定义表情键盘
    private lazy var emoticonKeyboard: WBEmoticonKeyboardView = {
        let view = WBEmoticonKeyboardView()
        view.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 216)
        return view
        }()
    
    // MARK: -  懒加载图片collectionview
    private lazy var pictureView: WBComposePictureView = WBComposePictureView()
    
    // MARK: -  懒加载文本输入框 WBComposeTextView
    private lazy var composeTextView: WBComposeTextView = {
        
        let composeTextView = WBComposeTextView()
        composeTextView.font = UIFont.systemFontOfSize(16)
        composeTextView.placeHolderString = "分享新鲜事..."
        composeTextView.delegate = self
        composeTextView.alwaysBounceVertical = true
        return composeTextView
    }()
    
    // MARK: -  懒加载titleView
    private lazy var titleView: UILabel = {
        
        let titleLabel = UILabel()
        
        let accountName = WBUserAccountTool.sharedAccountTool.userAccount?.screen_name ?? ""
        let titleString = "发微博\n\(accountName)"
        
        //副文本
        let attr = NSMutableAttributedString(string: titleString)
        
        let range = (titleString as NSString).rangeOfString(accountName)
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        attr.addAttribute(NSForegroundColorAttributeName, value: themeColor, range: range)
        titleLabel.attributedText = attr
        titleLabel.textAlignment = .Center
        titleLabel.numberOfLines = 0
        titleLabel.sizeToFit()
        
        return titleLabel
    }()
    
    // MARK: -  懒加载底部tabBar
    private lazy var composeToolBar: WBComposeToolBarView = WBComposeToolBarView()
    
    // MARK: -  移除通知观察者
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

// MARK: -  处理toolBar 里面的按钮点击事件
extension WBComposeViewController {
    
    // MARK: -  选择图片
    private func selectPictures() {
        
        let pictureVC = UIImagePickerController()
        pictureVC.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
            
            
        }else {
            
            print("不能打开相机")
            presentViewController(pictureVC, animated: true, completion: nil)
        }
        
    }
    
    // MARK: -  选择键盘
    func switchKeyborad() {
        
        if composeTextView.inputView == nil {
            
            composeTextView.inputView = emoticonKeyboard
            composeToolBar.isEmoticon = true
            
        }else {
            
            composeTextView.inputView = nil
            composeToolBar.isEmoticon = false
        }
        
        //刷新inputView
        composeTextView.reloadInputViews()
        composeTextView.becomeFirstResponder()
    }
}

// MARK: -  用户选择图片后的方法
extension WBComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    // MARK: -  用户选择图片后回调的方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        pictureView.addImage(image: getImageScale(image: image, width: 600))
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: -  压缩图片
    func getImageScale(image image: UIImage, width: CGFloat) -> UIImage {
        
        if image.size.width < width {
            
            return image
        }
        
        let height = (image.size.height * width) / image.size.width
        
        //开启图片上下文
        UIGraphicsBeginImageContext(CGSize(width: width, height: height))
        //把image渲染到上下文中
        image.drawInRect(CGRect(x: 0, y: 0, width: width, height: height))
        //得到结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return result
    }
}


// MARK: -  UITextView的代理方法
extension WBComposeViewController: UITextViewDelegate {
    
    // MARK: -  textView有文字的时候  导航栏右侧按钮可以点击
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    // MARK: -  scrollView开始滚动的时候
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        composeTextView.resignFirstResponder()
    }
}


// MARK: -  分类   发布微博
extension WBComposeViewController {
    
    // MARK: -  发送图片微博
    func releasePictureWeiBo(status: String){
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        let parma = [
            
            "access_token": WBUserAccountTool.sharedAccountTool.accessToken!,
            "status": status
        ]
        
      
        TMNetWorkTools.sharedTool.POST(urlString, parameters: parma, constructingBodyWithBlock: { (formData) -> Void in
            
            
            for image in self.pictureView.images {
                
                let data = UIImagePNGRepresentation(image)!
                
                formData.appendPartWithFileData(data, name: "pic", fileName: "xxx", mimeType: "image/jpeg")
            }
            
            }, success: { (_, response) -> Void in
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
                
            }) { (_, error) -> Void in
                
                SVProgressHUD.showErrorWithStatus("发送失败")
        }
        
        
    }
    
    
    // MARK: -  仅发送文字微博
    func releaseWordWeiBo(status: String) {
        
  
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let parma = [
            
            "access_token": WBUserAccountTool.sharedAccountTool.accessToken!,
            "status": status
        ]
        
        TMNetWorkTools.sharedTool.request("POST", urlString: urlString, param: parma) { (response, error) -> () in
            
            if error != nil {
                
                print("错误:\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")

        }
    }
}
